package com.bifrost.web.controller;

import com.bifrost.annotation.Authorization;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.annotation.CurrentUser;
import com.bifrost.constant.BonusPointsSource;
import com.bifrost.constant.BonusPointsUpdatedDetail;
import com.bifrost.constant.OrderReturnStatus;
import com.bifrost.entity.Customer;
import com.bifrost.entity.MerchantStore;
import com.bifrost.entity.Order;
import com.bifrost.entity.OrderItem;
import com.bifrost.common.model.ResultModel;
import com.bifrost.entity.OrderReturn;
import com.bifrost.entity.OrderType;
import com.bifrost.model.orderreturn.ReturnModel;
import com.bifrost.model.orderreturn.ReturnRequest;
import com.bifrost.service.BonusPointsService;
import com.bifrost.service.CustomerService;
import com.bifrost.service.OrderService;
import com.bifrost.service.ReturnService;
import com.bifrost.service.StoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Optional;

/**
 * @author rangf
 * @date 2017/11/22
 */

@RestController
@RequestMapping(value = "/api/return")
@Api("退货相关接口")
public class ReturnController {

    @Autowired
    OrderService orderService;
    @Autowired
    ReturnService returnService;
    @Autowired
    CustomerService customerService;
    @Autowired
    StoreService storeService;
    @Autowired
    BonusPointsService bonusPointsService;

    @Authorization
    @ApiOperation(value = "申请售后：单品")
    @ApiImplicitParam(paramType = "query", name = "request", value = "request entity", required = true, dataType = "String")
    @PostMapping("/apply")
    public ResultModel applyItem(@CurrentUser Long  userId, ReturnRequest request) {
        Customer customer = customerService.findCustomer(userId);
        Order order = orderService.findOrderByIdAndCustomer(request.getOrderId(), customer);
        if (returnService.canReturn(order)) {
            Optional<OrderItem> optional = order.getOrderItems().stream().filter(orderItem -> request.getSkuId().equals(orderItem.getSkuId())).findFirst();
            if (optional.isPresent()) {
                OrderItem item = optional.get();
                OrderReturn orderReturn = returnService.apply(customer, order, item, request);
                return ResultModel.ok("申请售后成功");
            }
        }
        return ResultModel.error("不能申请售后");
    }

    @Authorization
    @ApiOperation(value = "申请售后：整单")
    @ApiImplicitParam(paramType = "query", name = "request", value = "request entity", required = true, dataType = "String")
    @PostMapping("/applyOrder")
    public ResultModel applyOrder(@CurrentUser Long userId, ReturnRequest request) {
        Customer customer = customerService.findCustomer(userId);
        Order order = orderService.findOrderByIdAndCustomer(request.getOrderId(), customer);
        if(returnService.canReturn(order)) {
            try {
                returnService.applyAll(customer,order,request);
            }catch (Exception e){
               throw new RuntimeException("申请售后失败");
            }

            return ResultModel.ok("申请售后成功");
        }
        return ResultModel.error("不能申请售后");
    }


    @Authorization
    @ApiOperation(value = "获取所有售后单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String")
    })
    @GetMapping("/returns")
    public ResultModel orders(@CurrentStore Long storeId, @CurrentUser Long userId,
                              @RequestParam(value = "page", defaultValue = "1") String page,
                              @RequestParam(value = "pageSize", defaultValue = "10") String pageSize, String status
    ) {
        if(storeId != null){
            status = null;
            Customer customer = customerService.findCustomer(userId);
            List<ReturnModel> orders = returnService.orders(customer.getMerchantStore(),Integer.parseInt(page), Integer.parseInt(pageSize), customer, status);
            if (orders != null && !orders.isEmpty()) {
                return ResultModel.ok().put("orders", orders);
            }
            return ResultModel.ok("没有数据");
        }
        return ResultModel.ok("没有获取到门店信息");
    }

    @Authorization
    @ApiOperation("售后明细")
    @ApiImplicitParam(paramType = "query", name = "returnId", value = "售后Id", required = true, dataType = "Long")
    @GetMapping("/return")
    public ResultModel order(@RequestParam Long returnId) {
       return ResultModel.ok().put("return", returnService.order(returnId));
    }

    @Authorization
    @ApiOperation(value = "退货寄送商品")
    @PostMapping("/deliver")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "returnId", value = "returnId", required = false, dataType = "Long"),
            @ApiImplicitParam(paramType = "query", name = "shipNumber", value = "快递单号", required = false, dataType = "String"),
    })
    public ResultModel goods(@CurrentUser Long userId, @RequestParam Long returnId, @RequestParam String shipNumber) {
        Customer customer = customerService.findCustomer(userId);
        if (returnService.deliver(customer, returnId, shipNumber)) {
            return ResultModel.ok("配送成功");
        }
        return ResultModel.error("配送失败");
    }


    @Authorization
    @ApiOperation("取消退单")
    @ApiImplicitParam(paramType = "query", name = "售后Id", value = "售后Id", required = true, dataType = "Long")
    @PostMapping("/cancel")
    public ResultModel cancel(@CurrentUser Long userId, @RequestParam Long returnId) {
        Customer customer = customerService.findCustomer(userId);
        if (returnService.cancel(customer, returnId)) {
            return ResultModel.ok("撤销成功");
        }
        return ResultModel.error("撤销失败");
    }


}
